package leetcode.hashtable;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//1. 两数之和
public class TwoSum {
    public static void main(String[] args) {
        int[] data = {2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum3(data, 9)));

    }

    public static int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!hashMap.containsKey(target - nums[i])) {
                hashMap.put(nums[i], i);
            } else {
                return new int[]{i, hashMap.get(target - nums[i])};
            }
        }
        return null;

    }

    //哈希表
    public static int[] twoSum2(int[] numbers, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < numbers.length; i++) {
            if (!map.containsKey(target - numbers[i])) {
                map.put(numbers[i], i);
            } else {
                return new int[]{map.get(target - numbers[i]) + 1, i + 1};
            }
        }
        return null;
    }

    //双指针--错误
    public static int[] twoSum3(int[] numbers, int target) {

        Arrays.sort(numbers);
        int p = 0;
        int q = numbers.length - 1;
        while (p < q) {
            if (numbers[p] + numbers[q] > target) {
                q--;
            } else if (numbers[p] + numbers[q] < target) {
                p++;
            } else {
                return new int[]{p + 1, q + 1};
            }
        }
        return null;
    }

    //暴力
    public int[] twoSumP(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    //哈希表
    public int[] twoSumP2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(target - nums[i])) {
                map.put(nums[i], i);
            } else {
                return new int[]{i, map.get(target - nums[i])};
            }
        }
        return null;
    }

    //哈希表
    public int[] twoSumP3(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(target - nums[i])) {
                map.put(nums[i], i);
            } else {
                return new int[]{i, map.get(target - nums[i])};
            }
        }
        return null;
    }
}
